Skip to main content

Array filter

The .filter() method is a common array method. When you call this method on an array, you will receive another array containing some of the original array's items based on the condition you specify.

Consider the following example,

let numbers = [25, 56, 4, 52, 13, 12, 8, 46, 55];

let oddNumbers = numbers.filter(function (number) {
return number % 2;
});
console.log(oddNumbers); // [25, 13, 55]
Note

Don't forget the return keyword inside the callback function.

Take note of how we received a new array containing the items that met the condition. The condition is that the number be odd.

So, how exactly does this work?

Array.filter(callback)

Let's take a look at how the above code works by breaking it down step by step.

The first argument to the .filter() method is a callback. The callback in our example is:

function(number) {
return number % 2;
}

JavaScript will take your callback and execute it for each and every item in the array. Because our numbers array contains 5 items, it will be called 9 times. It will assign a value to the number parameter that you specified inside this callback every time it calls this function.

  • The first time it runs, it will assign a value of 25 to the number (the first item of the array).

  • The second time, a value of 56 is assigned to the number (the second item of the array).

  • and so on until the last element is assigned.

This is how callbacks work. Each array method has a unique behaviour, which we will explain. This behaviour is frequently determined by the outcome of the callback. If the callback function returns true in this case, the item will be included in the final array returned by .filter(). If the callback function returns false, the item will be removed from the final array.

That is, if you have the following code,

numbers.filter(function (number) {
return true;
});

This will return the entire array. As a result, you'll get a duplicate of the original array. This is due to the callback always returning true. This code isn't particularly useful, but it demonstrates the significance of what the callback function returns and how it affects the result of the .filter() method.

This is why we had a condition number % 2. Depending on the value of the number, this condition will return either true or false.